import { useSettingStore } from '@/store/bpmnProcess/settingStore'
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import { getBusinessObject, is } from 'bpmn-js/lib/util/ModelUtil'

export function isScriptTaskSupported(element) {
  return is(element, 'bpmn:ScriptTask')
}

export function getScriptTask(element) {
  const prefix = useSettingStore().editor.processEngine
  const businessObject = getBusinessObject(element)
  const result = {
    scriptFormat: businessObject.get('scriptFormat'),
    scriptType: getScriptType(businessObject),
    resultVariable: businessObject.get(`${prefix}:resultVariable`)
  }
  if (result.scriptType === 'inline') {
    result['script'] = businessObject.get('script')
    result['resource'] = ''
  } else if (result.scriptType === 'external') {
    result['script'] = ''
    result['resource'] = businessObject.get('resource')
  } else {
    result['script'] = ''
    result['resource'] = ''
  }
  return result
}

export function setScriptTask(element, type, value) {
  const prefix = useSettingStore().editor.processEngine
  const modeling = useModelerStore().getModeling
  const businessObject = getBusinessObject(element)
  if (type === 'type') {
    if (value === 'inline') {
      modeling.updateModdleProperties(element, businessObject, { resource: undefined, script: '' })
    } else if (value === 'external') {
      modeling.updateModdleProperties(element, businessObject, { resource: '', script: undefined })
    } else {
      modeling.updateModdleProperties(element, businessObject, { resource: undefined, script: undefined })
    }
  } else if (type === 'resultVariable') {
    modeling.updateModdleProperties(element, businessObject, { [`${prefix}:resultVariable`]: value })
  } else {
    modeling.updateModdleProperties(element, businessObject, { [type]: value })
  }
}

export function getScriptType(script): string {
  if (script.get('resource') !== undefined) {
    return 'external'
  }
  if (script.get('script') !== undefined) {
    return 'inline'
  }
  return ''
}
